package handlers

import (
	"github.com/gofiber/fiber/v2"
	"go_test/config"
	"go_test/core"
	"go_test/models"
)

func PageAll(c *fiber.Ctx) error {
	var reqs []models.LinkReq
	config.DB.Raw(`
		SELECT  a.*,  getlink.linkname AS linkName, yb.canUseCount, yb.successCount, 
		DATE_FORMAT(yb.latestTime, '%Y-%m-%d %H:%i:%S') latestTime,yb.nowCanUseCount
		FROM link_request a
		LEFT JOIN getlink ON a.link_code = getlink.linkcode
		LEFT JOIN (
			SELECT linkcode,
				SUM(CASE WHEN types = 1 AND NOW() BETWEEN startdate AND enddate THEN 1 ELSE 0 END) AS nowCanUseCount,
				SUM(CASE WHEN DATE(uptime) = CURRENT_DATE() THEN 1 ELSE 0 END) AS successCount,
				MIN(CASE WHEN startdate > NOW() THEN startdate END) AS latestTime,
				SUM(CASE WHEN startdate > NOW() THEN 1 ELSE 0 END) AS canUseCount
			FROM yibu GROUP BY linkcode
		) yb ON a.link_code = yb.linkcode
		WHERE a.user = ?
		ORDER BY a.remark, a.link_code DESC
	`, config.Custom.User).Scan(&reqs)

	// 设置 IsRunning 状态
	for i := range reqs {
		reqs[i].IsRunning = core.DefaultTaskManager().IsRunning(reqs[i].LinkCode)
	}

	return c.JSON(config.Success(reqs))
}

func SaveOrUpdateLinkReq(c *fiber.Ctx) error {
	var newLink models.LinkReq

	// 反序列化请求体
	if err := c.BodyParser(&newLink); err != nil {
		println(err.Error())
		return c.JSON(config.Error("Cannot parse JSON"))
	}

	// 分配新ID
	sql := `
		INSERT INTO link_request (
			link_code, app_id, version_type, idfa_type, region, proxy_type, 
			start_time, right_host, check_ip, allow_error_count, last_res, remark, user, 
			custom_version_ids, delay, af_ip
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON DUPLICATE KEY UPDATE
			app_id = VALUES(app_id),
			version_type = VALUES(version_type),
			idfa_type = VALUES(idfa_type),
			region = VALUES(region),
			proxy_type = VALUES(proxy_type),
			start_time = VALUES(start_time),
			right_host = VALUES(right_host),
			check_ip = VALUES(check_ip),
			allow_error_count = VALUES(allow_error_count),
			last_res = VALUES(last_res),
			remark = VALUES(remark),
			custom_version_ids = VALUES(custom_version_ids),
			delay = VALUES(delay),
			af_ip = VALUES(af_ip)
	`
	config.DB.Exec(sql,
		newLink.LinkCode,
		newLink.AppId,
		newLink.VersionType,
		newLink.IdfaType,
		newLink.Region,
		newLink.ProxyType,
		newLink.StartTime,
		newLink.RightHost,
		newLink.CheckIp,
		newLink.AllowErrorCount,
		newLink.LastRes,
		newLink.Remark,
		config.Custom.User,
		newLink.CustomVersionIds,
		newLink.Delay,
		newLink.AfIp,
	)
	// 修改参数后重启
	if core.DefaultTaskManager().IsRunning(newLink.LinkCode) {
		core.DefaultTaskManager().StopTask(newLink.LinkCode)
		core.DefaultTaskManager().StartTask(newLink)
	}
	return c.JSON(config.Success("操作成功"))
}
func StartTaskHandle(c *fiber.Ctx) error {
	var link models.LinkReq

	// 反序列化请求体
	if err := c.BodyParser(&link); err != nil {
		println(err.Error())
		return c.JSON(config.Error("Cannot parse JSON"))
	}
	core.DefaultTaskManager().StartTask(link)
	return c.JSON(config.Success("操作成功"))
}
func StopTaskHandle(c *fiber.Ctx) error {
	// 从查询参数中获取 linkCode
	linkCode := c.Query("linkCode")
	if linkCode == "" {
		return c.JSON(config.Error("linkCode 参数不能为空"))
	}
	// 停止定时任务
	core.DefaultTaskManager().StopTask(linkCode)

	return c.JSON(config.Success("操作成功"))
}
